<?php
// 获取用户提交的表单数据。
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$confirm = trim($_POST['confirm']);
$email = $_POST['email'];
$gender = isset($_POST['gender']) ? $_POST['gender'] : null;

// 连接数据库服务器。
include_once "../../conn.php";

// 后端验证输入。
if (!strlen($username) or !strlen($password)) {
    echo "<script>window.location.href = '../fail/index.html';</script>";
    exit;
} else {
    if (!preg_match('/^[a-zA-Z0-9]{1,32}$/', $username)) {
        echo "<script>window.location.href = '../fail/index.html';</script>";
        exit;
    }
}
if ($password <> $confirm) {
    echo "<script>window.location.href = '../fail/index.html';</script>";
    exit;
} else {
    if (!preg_match('/^[a-zA-Z0-9\-_=+*!#]{8,32}$/', $password)) {
        echo "<script>window.location.href = '../fail/index.html';</script>";
        exit;
    }
}
if (!empty($email)) {
    if (!preg_match('/^[a-zA-Z0-9\-_]+@([a-zA-Z0-9]+\.)+[a-zA-Z]{2,8}$/', $email)) {
        echo "<script>window.location.href = '../fail/index.html';</script>";
        exit;
    }
}

// 检查用户名是否已经占用。
$sql = "select * from `data` where username = '$username'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);
if ($num) {
    echo "<script>window.location.href = '../occupy/index.html';</script>";
    exit;
}

// 修改兴趣爱好写入数据库的格式。
if (!isset($_POST['hobbies'])) {
    $hobbies = "";
} else {
    $hobbies = $_POST['hobbies'];
    $hobbies = implode("、", $hobbies);
}

// 将数据插入至数据库。
$sql = "insert into `data` (creationtime, username, password, email, gender, hobbies) values ('" . time() . "','$username','" . md5($password) . "','$email','$gender','$hobbies')";

// 是否注册成功？！
$result = mysqli_query($conn, $sql);
if ($result) {
    echo "<script>window.location.href = '../succeed/index.html';</script>";
} else {
    echo "<script>window.location.href = '../fail/index.html';</script>";
}